﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sinacor.Infra.Core.Licensing;

namespace Sinacor.Infra.Core.Licensing
{
    public partial class ConsultarHistorico : Form
    {
        #region Campos
        Business.Licenca bussinesLicenca;
        Business.Historico bussinesHistorico;
        Business.Empresa bussinesEmpresa;
        Company companyAux;
        
        List<Company> listaEmpresa;        
        Licensing licensing;
        Licensing pesquisaHistorico;
        List<Licensing> listaHistorico;
        Common common;

        LicensingApplication licensingApplication;
        #endregion

        #region Construtor
        public ConsultarHistorico(LicensingApplication _licensingApplication)
        {
            InitializeComponent();
            Inicializar();
            licensingApplication = _licensingApplication;
        }
        public ConsultarHistorico(LicensingApplication _licensingApplication,Licensing _licensing)
        {
            InitializeComponent();
            Inicializar();

            licensingApplication = _licensingApplication;

            pesquisaHistorico.Id = _licensing.Id;
            txtIdLicenca.Text = pesquisaHistorico.Id.Value.ToString();

            listaHistorico = bussinesLicenca.SelecionarHistorico(pesquisaHistorico);

           dgvHistorico.DataSource = null;
           dgvHistorico.AutoGenerateColumns = false;
           dgvHistorico.DataSource = listaHistorico;

        }

        #endregion

        #region Evento
        private void btnPesquisar_Click(object sender, EventArgs e)
        {
            #region Pesquisa

            #region Id Licença
            if (string.IsNullOrEmpty(txtIdLicenca.Text))
                pesquisaHistorico.Id  = null;
            else
                pesquisaHistorico.Id = Convert.ToInt32(txtIdLicenca.Text);
            #endregion

            #region CNPJ Raiz
            if (cboCNPJ.SelectedValue == null)
                pesquisaHistorico.OwnerLegalRegistrationId = null;
            else
                pesquisaHistorico.OwnerLegalRegistrationId = common.DesformatarCNPJ(cboCNPJ.SelectedValue.ToString()); 
            #endregion

            #region Created
            if (!dtpDataHistorico.Checked)
                pesquisaHistorico.Description.Period= null;
            else
                pesquisaHistorico.Description.Period = Convert.ToDateTime(dtpDataHistorico.Text);
            #endregion

            #region Tipo Histórico

            if (cboTipoHistorico.SelectedIndex  == 0)
                pesquisaHistorico.Description.TypeDescription = null;
            else
                pesquisaHistorico.Description.TypeDescription = (TypeDescription?)cboTipoHistorico.SelectedItem;
            #endregion

         
            #endregion

            listaHistorico = bussinesLicenca.SelecionarHistorico(pesquisaHistorico);
            dgvHistorico.AutoGenerateColumns = false;
            dgvHistorico.DataSource = listaHistorico;

            if (listaHistorico.Count == 0)
                MessageBox.Show("Não foram encontrados dados que satisfaçam a pesquisa.");
            else
                dgvHistorico.CurrentRow.Selected = false;                
        }

        private void btnNovaPesquisa_Click(object sender, EventArgs e)
        {
            #region Pesquisa

            btnRestaurar.Enabled = false;

            txtIdLicenca.Clear();
            cboCNPJ.SelectedIndex = -1;
            dtpDataHistorico.Value = DateTime.Now; 
            dtpDataHistorico.Checked = false;
            

            cboTipoHistorico.SelectedItem = "";
            dgvHistorico.DataSource = null;

            btnRestaurar.Enabled = false;
            dgvHistorico.DataSource = null; 
            
            #endregion
        }

        private void dgvHistorico_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;

            if (grid.CurrentCell != null && !grid.CurrentRow.Selected)
            {
                grid.Rows[grid.CurrentCell.RowIndex].Selected = true;
                dgvHistorico_RowHeaderMouseClick(sender, e);
            }
        }
        private void dgvHistorico_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            
            DataGridView grid = (DataGridView)sender;

            #region parametros Licensing

            licensing.Description.TypeDescription = (TypeDescription)grid.CurrentRow.Cells["TypeDescription"].Value;

            if (licensing.Description.TypeDescription == Sinacor.Infra.Core.Licensing.TypeDescription.Excluir ||
                licensing.Description.TypeDescription == Sinacor.Infra.Core.Licensing.TypeDescription.Restaurar)
            {
                btnRestaurar.Enabled = false;
                return;
            }
            else
                btnRestaurar.Enabled = true;

            licensing.Id = Convert.ToInt32(grid.CurrentRow.Cells["Id"].Value);
            licensing.Description.Id = Convert.ToInt32(grid.CurrentRow.Cells["IdHistorico"].Value);
            licensing.Description.LicensingId = licensing.Id;

            licensing.Description.Period = Convert.ToDateTime(grid.CurrentRow.Cells["Period"].Value);
            licensing.Active = Sinacor.Infra.Core.Licensing.Active.Ativo;
            licensing.Description.User = Environment.UserName;

            licensing.Description.Annotation = "Cometário Restaurar ";

            licensing.Created = DateTime.Now;
            licensing.OwnerLegalRegistrationId = common.DesformatarCNPJ(grid.CurrentRow.Cells["OwnerLegalRegistrationId"].Value.ToString());
            licensing.Treaty = (Treaty)grid.CurrentRow.Cells["Treaty"].Value;

            #endregion

        }
                
        private void dgvHistorico_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
           DataGridView grid = (DataGridView)sender;
           Description description;

           foreach (DataGridViewRow row in grid.Rows)
           {
               description = (Description)row.Cells["Historico"].Value;


               row.Cells["OwnerLegalRegistrationId"].Value = common.FormatarCNPJ(row.Cells["OwnerLegalRegistrationId"].Value.ToString());  

               row.Cells["IdHistorico"].Value = description.Id.ToString();
               row.Cells["Period"].Value = description.Period;
               row.Cells["TypeDescription"].Value = description.TypeDescription;

               row.Cells["User"].Value = description.User;
               row.Cells["Annotation"].Value = description.Annotation;
           }

           if (grid.Rows.Count != 0)
               grid.Rows[0].Selected = false;
        }

        private void ConsultarHistorico_Load()
        {
        }

        private void btnRestaurar_Click(object sender, EventArgs e)
        {
            if (dgvHistorico.CurrentRow.Selected)
            {
                bussinesLicenca.Restaurar(licensing) ;

                licensingApplication.btnNovaPesquisa_Click(sender, e);

                MessageBox.Show("Restauração realizada com sucesso.");
                Close(); 
            }
            else
                MessageBox.Show("Selecione um histórico para restaurar"); 
        }

        private void ConsultarHistorico_Activated(object sender, EventArgs e)
        {
            if (listaHistorico.Count != 0)
            {
                if (dgvHistorico.CurrentRow != null)
                      dgvHistorico.CurrentRow.Selected = false;
            }
        }

        #endregion

        #region Metodo
        private void CarregarTipoHistorico()
        {
            cboTipoHistorico.Items.Add("");
            cboTipoHistorico.Items.Add(Sinacor.Infra.Core.Licensing.TypeDescription.Alterar);
            cboTipoHistorico.Items.Add(Sinacor.Infra.Core.Licensing.TypeDescription.Excluir);
            cboTipoHistorico.Items.Add(Sinacor.Infra.Core.Licensing.TypeDescription.Incluir);
            cboTipoHistorico.Items.Add(Sinacor.Infra.Core.Licensing.TypeDescription.Restaurar);

            cboTipoHistorico.SelectedIndex = -1;
        }
        
        private void Inicializar()
        {
            common = new Common();
            listaHistorico = new List<Licensing>();
            bussinesLicenca = new Business.Licenca();
            bussinesHistorico = new Business.Historico();
            bussinesEmpresa = new Business.Empresa();

            pesquisaHistorico = new Licensing();
            pesquisaHistorico.Description  = new Description();

            licensing = new Licensing();
            licensing.Description = new Description(); 
            CarregarTipoHistorico();

            dgvHistorico.AutoGenerateColumns = false;
            dgvHistorico.DataSource = listaHistorico;
            companyAux = new Company();
            listaEmpresa = bussinesEmpresa.Selecionar(companyAux);
            
            CarregarEmpresa();
        }
        private void CarregarEmpresa()
        {
            cboCNPJ.DataSource = null;            
            List<string> listaCNPJ = new List<string>();
            string cnpjAux = "";
            bool encontrarCNPJ = false;
            foreach (var item in listaEmpresa)
            {
                cnpjAux = common.FormatarCNPJ(item.LegalRegistrationId);

                if (listaCNPJ.Count == 0)
                    listaCNPJ.Add(cnpjAux);
                else
                {
                    foreach (string itemCNPJ in listaCNPJ)
                    {
                        if (itemCNPJ.Contains(cnpjAux))
                        {
                            encontrarCNPJ = true;
                            break;
                        }
                    }
                    if (!encontrarCNPJ)
                        listaCNPJ.Add(cnpjAux);
                }                
            }
            listaCNPJ.Insert(0, "");
            listaCNPJ.Sort();

            cboCNPJ.DataSource = listaCNPJ;
        }

        #endregion

        private void txtIdLicenca_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
                e.Handled = true;
        }
    }        
}
